package web.servlet.profilePhoto;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.ProfilePhoto;
import domain.response.FindNewestPhotoResponse;
import service.ProfilePhotoService;
import service.impl.ProfilePhotoServiceImpl;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/findNewestPhoto")
public class FindNewestPhotoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        LyyLogUtil.logD("userId: "+userId);
        ProfilePhotoService service=new ProfilePhotoServiceImpl();
        ProfilePhoto newestPhoto=null;
        Exception exception=null;
        try {
            newestPhoto = service.findNewestPhoto(userId);
            LyyLogUtil.logD("头像："+newestPhoto.toString());
        } catch (Exception e) {
            exception=e;
            e.printStackTrace();
        }
        FindNewestPhotoResponse findNewestPhotoResponse=new FindNewestPhotoResponse();
        if(exception!=null){
            findNewestPhotoResponse.setStatus(0);
            findNewestPhotoResponse.setErrMsg(exception.getMessage());
        }else {
            if(newestPhoto!=null&&newestPhoto.getPictureStr()!=null){
                String pictureStr =newestPhoto.getPictureStr();
                findNewestPhotoResponse.setPictureStr(pictureStr);
            }else {
                findNewestPhotoResponse.setStatus(0);
                findNewestPhotoResponse.setErrMsg("未找到该用户的头像信息！");
            }
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(),findNewestPhotoResponse);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
